package com.zhaoqi.hr.repository;

import com.zhaoqi.hr.entity.WorkerProfile;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;

/**
 * 劳动者档案数据访问层
 */
@Repository
public interface WorkerProfileRepository extends JpaRepository<WorkerProfile, Long> {

    /**
     * 根据用户ID查找劳动者档案
     */
    Optional<WorkerProfile> findByUserId(Long userId);
    
    /**
     * 根据ID查找劳动者档案并主动加载User关联
     */
    @Query("SELECT w FROM WorkerProfile w LEFT JOIN FETCH w.user WHERE w.id = :id")
    Optional<WorkerProfile> findByIdWithUser(@Param("id") Long id);
    
    /**
     * 分页查找所有劳动者档案并主动加载User关联
     */
    @Query(value = "SELECT w FROM WorkerProfile w LEFT JOIN FETCH w.user",
           countQuery = "SELECT COUNT(w) FROM WorkerProfile w")
    Page<WorkerProfile> findAllWithUser(Pageable pageable);

    /**
     * 根据技能标签查找劳动者
     */
    @Query("SELECT w FROM WorkerProfile w WHERE w.skills LIKE %:skill%")
    List<WorkerProfile> findBySkillsContaining(@Param("skill") String skill);

    /**
     * 根据期望薪资范围查找劳动者
     */
    List<WorkerProfile> findByExpectedSalaryBetween(BigDecimal minSalary, BigDecimal maxSalary);

    /**
     * 根据工作半径查找劳动者
     */
    List<WorkerProfile> findByWorkRadiusLessThanEqual(Integer radius);

    /**
     * 根据评分查找劳动者
     */
    List<WorkerProfile> findByRatingGreaterThanEqual(BigDecimal minRating);

    /**
     * 查找完成工作数量最多的劳动者
     */
    List<WorkerProfile> findTop10ByOrderByCompletedJobsDesc();

    /**
     * 统计劳动者技能分布
     */
    @Query("SELECT w.skills, COUNT(w) FROM WorkerProfile w GROUP BY w.skills")
    List<Object[]> countBySkills();
}
